<?php
namespace app\common\search;

/**
 * 提供搜索条件
 */
class Base {
	protected $request = null;

	public function __construct($request = null) {
		$request = $request ? $request : $this->request;
		$this->setRequest($request);
	}

	//更换数据收集器
	public function setRequest($request) {
		if(is_string($request)) {
			$request = loader()->loadAny('request', $request);
		}
		$this->request = $request;
	}

	/*
	 *  根据模型是否有别名来生成查询条件的key
	 *  $model->alias('a');
	 *  $key = $this->get_search_key($model, 'status');
	 *  echo $key;
	 *  打印a.status
	 */
	public function get_search_key($model, $key) {
		if($model->aliasName) {
			$key = $model->aliasName . '.' . $key;
		}
		return $key;
	}

	public function search($model, $post = null) {
		$post = $this->request->post();
		foreach($post as $k => $v) {
			$model->where($k, $v);
		}
		return $model;
	}

	//批量处理参数
	public function search4arr($model, $arr, $post) {
		foreach($arr as $k => $v) {
			if(method_exists($this, $v)) {
				$this->$v($model, $post);
			} else {
				$key = $this->get_search_key($model, $v);
				$model->where($key, $post[$v]);
			}
		}
	}

	//对列表排序
	public function order($model) {
		$order = $this->request->get_order();
		$order_type = $this->request->get_order_type();
		$model->order($order . ' ' . $order_type);
	}
}
